package me.keiwu.user.controller;

import com.alibaba.fastjson.JSONObject;
import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.util.ContextUtil;
import me.keiwu.user.domain.UserForm;
import me.keiwu.user.rpc.ConfigRpc;
import me.keiwu.user.service.UserService;
import me.keiwu.pub.data.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by kei on 08/11/2017.
 */
@RestController
@RequestMapping("/")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private ConfigRpc configRpc;

	@ResponseBody
	@RequestMapping("user/info")
	public Response userInfo(HttpServletRequest request, @RequestParam(required = false) Long userId) {
		Long loginUid = ContextUtil.getLoginUserId(request);
		JSONObject json = new JSONObject();
		if (userId == null || loginUid.equals(userId)) {
			// 查看自己
			json.put("userInfo", userService.getUserInfoCache(loginUid));
			json.put("config", configRpc.getAllConfig());
		} else {
			// 查看别人
			json.put("otherUserInfo", userService.getOtherUserInfo(userId));
		}
		return Response.ok(json);
	}

	@RequestMapping("/shareGetGold")
	public ResponseV2 shareGetGold(HttpServletRequest request) {
		Long userId = ContextUtil.getLoginUserId(request);
		return userService.shareGetGold(userId);
	}

	@RequestMapping("/userForm/saveUserForm")
	public ResponseV2 saveUserForm(HttpServletRequest request,String formId, String action) {
		UserForm userForm = new UserForm();
		// 获取userid
		Long userId = ContextUtil.getLoginUserId(request);
		// TODO 需要赋值，保存到数据库
		userForm.setUserId(userId);
		userForm.setFormId(formId);
		userForm.setAction(action);
		userService.saveUserForm(userForm);
		return ResponseV2.ok("保存成功");
	}

	@RequestMapping("/userForm/getUserForm")
	public UserForm getUserForm(HttpServletRequest request) {
		Long userId = ContextUtil.getLoginUserId(request);
		return userService.getOldestUserFormById(userId);
	}

}
